package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FolLOWS_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private IUserService userService;

    /**
     * 关注或取关
     * @param followId
     * @param isFollow
     * @return
     */
    @Override
    public Result follow(Long followId, Boolean isFollow) {
        //1、获取当前用户id
        Long userId = UserHolder.getUser().getId();
        //设置集合键
        String key = FolLOWS_KEY + userId;

        //1。1、查询是关注还是取关
        if (isFollow)
        {
            //2、关注-新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followId);
            boolean isSuccss = save(follow);

            //2，1将数据存入Redis集合中
            if (isSuccss)
            {
                stringRedisTemplate.opsForSet().add(key, followId.toString());
            }
        }
        else {

            //3、取关-删除数据
            boolean isSuccss = remove(new QueryWrapper<Follow>()
                    .eq("user_id", UserHolder.getUser().getId())
                    .eq("follow_user_id", followId));

            //3.1、删除数据成功，更新redis
            if (isSuccss)
                stringRedisTemplate.opsForSet().remove(key, followId.toString());
        }

        return Result.ok();
    }

    /**
     * 判断当前用户是否关注了某个用户
     * @param followId
     * @return
     */
    @Override
    public Result isFollow(Long followId) {
        //判断当前用户是否关注了某个用户，就看是否有数据就得了
        Integer count = query().eq("user_id", UserHolder.getUser().getId()).count();

        return Result.ok(count > 0);
    }

    /**
     * 共同关注
     * @param id
     * @return
     */
    @Override
    public Result followCommons(Long id) {
        //1、查询当前用户id并设置key
        Long userId = UserHolder.getUser().getId();
        //设置集合键
        String key1 = FolLOWS_KEY + userId;
        //2、求交集、
        String key2 = FolLOWS_KEY + id;

        Set<String> ids = stringRedisTemplate.opsForSet().intersect(key1, key2);

        if (ids == null || ids.isEmpty())//无交集
            return Result.ok(Collections.emptyList());

        //3、解析ids集合转为long类型
        List<Long> idsLong = ids.stream().map(Long::valueOf).collect(Collectors.toList());


        //4、封装成UserDTO返回
        List<UserDTO> userDTOS = userService.listByIds(idsLong)
                .stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        return Result.ok(userDTOS);
    }
}
